from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator

from .models import UserFav, UserAddress
from goods.serializers import GoodListSerializer


class UserFavDetailSerializer(serializers.ModelSerializer):
    good = GoodListSerializer()

    class Meta:
        model = UserFav
        fields = ("good", "id")


class UserFavSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )

    class Meta:
        model = UserFav
        validators = [
            UniqueTogetherValidator(
                queryset=UserFav.objects.all(),
                fields=('user', 'good'),
                message="请不要重复收藏喔~"
            )
        ]

        fields = ("user", "good", "id")


class AddressSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )
    add_time = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M')

    def validate_isDefault(self, is_default):
        if is_default:
            user_id = self.context['request'].user.id
            queryset = UserAddress.objects.filter(isDefault=True, user_id=user_id)
            for item in queryset:
                item.isDefault = False
                item.save()
        return is_default

    class Meta:
        model = UserAddress
        fields = (
            "id", "user", "province", "city", "district", "address", "areaCode", "signer_name", "add_time",
            "signer_mobile", "isDefault")
